package com.ql.dev.customwebview.library.views;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.ql.dev.customwebview.library.R;
import com.ql.dev.customwebview.library.dialog.UploadPopup;
import com.ql.dev.customwebview.library.utils.StringUtils;

/**
 * Created by Quanguanzhou on  2017/3/22 0022.
 * Copyright (c) 2015, quanguanzhou83@gmail.com All Rights Reserved.
 */
public class CustomWebView extends LinearLayout {
    private Context mContext;
    private View rootView;
    private RelativeLayout navWebView;
    private LinearLayout llLeftBack;
    private TextView tvLeftBack;
    private LinearLayout llLeftClose;
    private TextView tvLeftClose;
    private LinearLayout llCenter;
    private TextView tvCenter;
    public LinearLayout llRight;
    private TextView tvRight;
    private ImageView ivRight;
    private ProgressBar pbGress;
    private WebView wvWebview;
    private Params param;

    private CustomWebView(Context mContext) {
        super(mContext);
        this.mContext = mContext;
    }

    private CustomWebView(Context mContext, AttributeSet attrs) {
        super(mContext, attrs);
        this.mContext = mContext;
    }

    private CustomWebView(Context mContext, AttributeSet attrs, int defStyleAttr) {
        super(mContext, attrs, defStyleAttr);
        this.mContext = mContext;
    }

    private void initView() {
        LayoutInflater layoutInflater = LayoutInflater.from(mContext);
        rootView = (ViewGroup) layoutInflater.inflate(R.layout.custom_view_webview, this);
        rootView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        navWebView = (RelativeLayout) rootView.findViewById(R.id.navWebView);
        llLeftBack = (LinearLayout) rootView.findViewById(R.id.llLeftBack);
        tvLeftBack = (TextView) rootView.findViewById(R.id.tvLeftBack);
        llLeftClose = (LinearLayout) rootView.findViewById(R.id.llLeftClose);
        tvLeftClose = (TextView) rootView.findViewById(R.id.tvLeftClose);
        llCenter = (LinearLayout) rootView.findViewById(R.id.llCenter);
        tvCenter = (TextView) rootView.findViewById(R.id.tvCenter);
        llRight = (LinearLayout) rootView.findViewById(R.id.llRight);
        tvRight = (TextView) rootView.findViewById(R.id.tvRight);
        ivRight = (ImageView) rootView.findViewById(R.id.ivRight);
        pbGress = (ProgressBar) rootView.findViewById(R.id.pbGress);
        wvWebview = (WebView) rootView.findViewById(R.id.wvWebview);
        initListener();
        setPageProperty();
    }

    private void setPageProperty() {
        if(param.navigationView){
            if(!StringUtils.isEmpty(param.isRefresh)){
                if(param.isRefresh.equals("0")) {
                    tvRight.setVisibility(GONE);
                }else{
                    tvRight.setVisibility(VISIBLE);
                    tvRight.setTextColor(getResources().getColor(param.rightFontColor));
                    if(!StringUtils.isEmpty(param.rightValue)){
                        tvRight.setText(param.rightValue);
                        Drawable drawable = getResources().getDrawable(param.rightLeftPicResId);
                        tvRight.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null);
                    }
                }
            }
            if(!StringUtils.isEmpty(param.isShowBack)){
                if(param.isShowBack.equals("0")) {
                    tvLeftBack.setVisibility(GONE);
                }else{
                    tvLeftBack.setVisibility(VISIBLE);
                    Drawable drawable= getResources().getDrawable(param.backPic);
                    tvLeftBack.setTextColor(getResources().getColor(param.backfontColor));
                    tvLeftBack.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null);
                }
            }
            if(!StringUtils.isEmpty(param.isShowClose)){
                if(param.isShowClose.equals("0")) {
                    tvLeftClose.setVisibility(GONE);
                }else{
                    tvLeftClose.setVisibility(VISIBLE);
                    tvLeftClose.setTextColor(getResources().getColor(param.closeFontColor));
                }
            }
            tvCenter.setTextColor(getResources().getColor(param.centerFontColor));
            navWebView.setBackgroundColor(getResources().getColor(param.backColor));

            llLeftBack.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (param.onNavigationCallbackListener != null) {
                        param.onNavigationCallbackListener.doLeftbackListener(wvWebview,param.activity);
                    }
                }
            });
            llLeftClose.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (param.onNavigationCallbackListener != null) {
                        param.onNavigationCallbackListener.doLeftCloseListener(wvWebview,param.activity);
                    }
                }
            });
            llRight.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (param.onNavigationCallbackListener != null) {
                        param.onNavigationCallbackListener.doRightCallbackListener(wvWebview,param.activity);
                    }
                }
            });

            tvCenter.setText(param.centerTitle);
            navWebView.setVisibility(VISIBLE);
        }else{
            navWebView.setVisibility(GONE);
        }

    }

    private void initListener() {
        try {
            wvWebview.setWebChromeClient(new MyWebChromClient(pbGress, param.hostJsScopeClass,param.onWebViewChromListener));
            //获取WebSettings对象
            WebSettings settings = wvWebview.getSettings();
            //设置是否启用支持javascript
            settings.setJavaScriptEnabled(param.javaScriptEnabled);
            settings.setDomStorageEnabled(param.domStorageEnabled);
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
            //页面使用了HTTPs和HTTP混合的方式
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            //设置缓存策略
            settings.setCacheMode(param.cacheMode);
            wvWebview.setWebViewClient(new MyWebViewClient(param.activity,param.openBySystem,param.onWebViewClientListener));
            wvWebview.setOverScrollMode(param.overScrollMode);
            wvWebview.loadUrl(param.url);
            wvWebview.setOnLongClickListener(new OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    WebView.HitTestResult result = ((WebView) v).getHitTestResult();
                    if (null == result) {
                        return false;
                    }
                    int type = result.getType();
                    if(WebView.HitTestResult.IMAGE_TYPE == type){ // 长按图片弹对话框，进行保存图片
                        String imgurl = result.getExtra();
                        UploadPopup uploadPopup = doInitUploadPopup(R.id.wvWebview,imgurl);
                        uploadPopup.setValues(false,"",false,"","保存图片","取消");
                        uploadPopup.initPopWindowUploadHeader();
                    }
                    return false;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 弹出Dialog
     *
     * @param layoutId
     * @return
     */
    private UploadPopup doInitUploadPopup(int layoutId,final String imgurl) {
        final UploadPopup uploadPopup = new UploadPopup((Activity) mContext, layoutId, new UploadPopup.UploadListener() {
            @Override
            public void onClickChooseCancel() { // 取消

            }

            @Override
            public void onClickChoosePicListener() { // 查看图片

            }

            @Override
            public void onClickTaskPhotoListener() {  //保存图片
                WebViewDownload webViewDownload = new WebViewDownload((Activity) mContext,imgurl);
                webViewDownload.execute();
            }
        });
        return uploadPopup;
    }

    public void setParam(Params param) {
        this.param = param;
    }

    /**
     * 对于WebView的使用可以参考：https://jiandanxinli.github.io/2016-08-31.html
     */
    public static class Builder {

        public Activity context;
        public Params params = new Params();
        private ViewGroup contentView;
        private CustomWebView customWebView;

        /**
         * Create a builder for an cookie.
         *
         * @param activity
         * @param contentView
         */
        public Builder(Activity activity, ViewGroup contentView) {
            this.context = activity;
            this.contentView = contentView;
            params.activity = activity;
        }

        /**
         * 设置加载的Url,不能为空
         *
         * @param url
         * @return
         */
        public Builder setUrl(@NonNull String url) {
            params.url = url;
            return this;
        }

        /**
         * 设置是否支持Js，如果不设置默认为支持
         *
         * @param javaScriptEnabled
         * @return
         */
        public Builder setJavaScriptEnabled(boolean javaScriptEnabled) {
            params.javaScriptEnabled = javaScriptEnabled;
            return this;
        }

        /**
         * 设置是否支持Dom储存
         *
         * @param domStorageEnabled
         * @return
         */
        public Builder setDomStorageEnabled(boolean domStorageEnabled) {
            params.domStorageEnabled = domStorageEnabled;
            return this;
        }

        /**
         * 设置缓存策略，可以不用设置，默认为：WebSettings.LOAD_CACHE_ELSE_NETWORK
         *
         * @param cacheMode
         * @return
         */
        public Builder setCacheMode(@NonNull int cacheMode) {
            params.cacheMode = cacheMode;
            return this;
        }

        /**
         * 当不需要WebView的导航的时候进行设置隐藏
         * @param isVisiable
         */
        public Builder setNaivagationIsVisiable(boolean isVisiable){
            params.navigationView = isVisiable;
            return this;
        }

        /**
         * 设置页面中间的标题
         *
         * @param title
         * @return
         */
        public Builder setPageCenterTitle(@NonNull String title) {
            params.centerTitle = title;
            return this;
        }

        /**
         * 设置导航条返回、关闭、刷新的点击事件，可以不用设置使用默认的
         *
         * @param onNavigationCallbackListener
         * @return
         */
        public Builder setNavigationCallbackListener(OnNavigationCallbackListener onNavigationCallbackListener) {
            params.onNavigationCallbackListener = onNavigationCallbackListener;
            return this;
        }

        /**
         *
         * @param onWebViewChromListener
         * @return
         */
        public Builder setOnWebViewChromListener(OnWebViewChromListener onWebViewChromListener){
            params.onWebViewChromListener = onWebViewChromListener;
            return this;
        }

        public Builder setOnWebViewClientListener(OnWebViewClientListener onWebViewClientListener){
            params.onWebViewClientListener = onWebViewClientListener;
            return this;
        }

        /**
         * 设置返回的图片
         * @param backPic
         * @return
         */
        public Builder setBackPic(int backPic){
            params.backPic = backPic;
            return this;
        }

        /**
         * 设置返回字体颜色
         * @param fontColor
         * @return
         */
        public Builder setBackFontColor(int fontColor){
            params.backfontColor = fontColor;
            return this;
        }

        /**
         * 设置关闭的字体颜色
         * @param fontColor
         * @return
         */
        public Builder setCloseFontColor(int fontColor){
            params.closeFontColor = fontColor;
            return this;
        }

        /**
         * 设置标题字体颜色
         * @param fontColor
         * @return
         */
        public Builder setCenterFontColor(int fontColor){
            params.centerFontColor = fontColor;
            return this;
        }

        /**
         * 设置右边字体颜色
         * @param fontColor
         * @return
         */
        public Builder setRightFontColor(int fontColor){
            params.rightFontColor = fontColor;
            return this;
        }

        /**
         * 设置背景颜色
         * @param backColor
         * @return
         */
        public Builder setBackColor(int backColor){
            params.backColor = backColor;
            return this;
        }

        /**
         * 设置此属性之前，先保证设置了.setIsRefresh("1")，让其显示
         * @return
         */
        public Builder setRightValueAndLeftPic(String rightValue,int resId){
            params.rightValue = rightValue;
            params.rightLeftPicResId = resId;
            return this;
        }

        public void create() {
            customWebView = new CustomWebView(context);
            customWebView.setParam(params);
            customWebView.initView();
            contentView.addView(customWebView, 0);
        }

        public void onDestroy() {
            if(customWebView!=null) {
                customWebView.onDestroy();
            }
        }
        public WebView getWebView(){
            if(customWebView!=null) {
                return customWebView.getWebView();
            }else{
                return null;
            }
        }

        public Builder setIsShowBack(String isShowBack) {
           params.isShowBack = isShowBack;
            return this;
        }

        public Builder setIsShowClose(String isShowClose) {
            params.isShowClose = isShowClose;
            return this;
        }

        public Builder setIsRefresh(String isRefresh) {
            params.isRefresh = isRefresh;
            return this;
        }

        public Builder setOpenBySystem(String openBySystem) {
            params.openBySystem = openBySystem;
            return this;
        }

        public Builder setHostJsScopeClass(Class<? extends HostJsScope> hostJsScopeClass) {
            params.hostJsScopeClass = hostJsScopeClass;
            return this;
        }

        public Builder setOverScrollMode(int overScrollMode){
            params.overScrollMode = overScrollMode;
            return this;
        }
    }

    final static class Params {
        Activity activity;
        String isShowBack; //是否显示返回 1是0否

        String isShowClose;//是否显示关闭 1是0否

        String isRefresh;//是否显示刷新 1是0否
        /**
         * 需要显示的Url，可以是：file:///android_asset/、可以是Http、Https网址
         */
        String url;
        /**
         * 返回的图片
         */
        int backPic;
        /**
         * 设置返回的的字体颜色
         */
        int backfontColor;
        /**
         * 设置关闭的字体颜色
         */
        int closeFontColor;
        /**
         * 设置标题的字体颜色
         */
        int centerFontColor;
        /**
         * 设置右边的字体颜色
         */
        int rightFontColor;
        /**
         * 设置右边的文字
         */
        String rightValue;
        /**
         * 设置右边文字左边的图标
         */
        int rightLeftPicResId;
        /**
         * 导航条的背景颜色
         */
        int backColor;
        /**
         * WebView中的连接是否用系统浏览器打开
         * 默认不用系统浏览器打开
         */
        String openBySystem = "0";
        /**
         * 是否启用Js，默认为启用
         */
        boolean javaScriptEnabled = true;
        /**
         * 缓存模式，默认为：WebSettings.LOAD_NO_CACHE;
         */
        int cacheMode = WebSettings.LOAD_NO_CACHE;
        /**
         * 页面标题
         */
        String centerTitle;
        /**
         * CustomWebView，返回、关闭、刷新的自定义点击事件
         */
        OnNavigationCallbackListener onNavigationCallbackListener;

        OnWebViewChromListener onWebViewChromListener;

        OnWebViewClientListener onWebViewClientListener;
        /**
         * DOM储存
         */
        boolean domStorageEnabled = true;
        /**
         * 设置自定义的处理类
         */
        Class<? extends HostJsScope> hostJsScopeClass;
        /**
         * 是否显示默认的导航，默认显示
         */
        boolean navigationView = true;
        /**
         * WebView的ScrollMode
         */
        int overScrollMode = View.OVER_SCROLL_NEVER;
    }
    private void onDestroy() {
        wvWebview.destroy();
    }

    private WebView getWebView(){
        return wvWebview;
    }
}
